package com.zyg.page.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.common.utils.PageUtils;
import com.zyg.common.utils.Query;
import com.zyg.page.dao.ItemDao;
import com.zyg.page.entity.ItemEntity;
import com.zyg.page.service.GoodsService;
import com.zyg.page.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("itemService")
public class ItemServiceImpl extends ServiceImpl<ItemDao, ItemEntity> implements ItemService {
    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private GoodsService goodsService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ItemEntity> page = this.page(
                new Query<ItemEntity>().getPage(params),
                new QueryWrapper<ItemEntity>()
        );

        return new PageUtils(page);
    }

    //1. 根据spu商品id，查询sku列表，并更新到索引库中
    @Override
    public void updateToIndex(Long id) {
        //1.1 根据spu商品id得到sku列表
        List<ItemEntity> items = this.list(new QueryWrapper<ItemEntity>().eq("goods_id", id));
        System.out.println("items=" + items);
        //1.2 同步到索引库中
        restTemplate.save(items);
        //提示
        System.out.println("同步到索引库成功！");
    }


    //2. 从索引库中删除数据
    @Override
    public void removeFromIndex(Long[] ids) {
//        for (Long id : ids) {
//           //2.1 根据外键id在tb_item表中查询出sku商品列表
//            List<Long> goodsIds = this.list(new QueryWrapper<ItemEntity>()
//                                        .eq("goods_id", id)).stream()
//                                        .map(m -> m.getId()).collect(Collectors.toList());
//            //2.2 构造要删除的对象的条件
//            Criteria criteria = new Criteria("id").in(goodsIds);
//            CriteriaQuery query = new CriteriaQuery(criteria);
//            //2.3 根据条件从索引库中删除
//            restTemplate.delete(query,ItemEntity.class, IndexCoordinates.of("item"));
//        }
//        System.out.println("从索引库中删除数据成功！");
    }

}